package com.yb0os1.SimpleJDKProxy;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;


public class ProxyFactory {
    private static final AtomicInteger count = new AtomicInteger(0);

    //创建Java文件 代理对象
    //哪些东西是动态的？包名 类名 函数体
    private static String packageName = "com.yb0os1.SimpleJDKProxy";
    private static File createJavaFile(String className, MyHandler myHandler) throws IOException {

        String context = "package "+packageName+";\n" +
                "public class " + className + " implements MyInterface{\n" +
                "    MyInterface myInterface;\n" +
                "    @Override\n" +
                "    public void fun1() { \n" +
                myHandler.functionBody("fun1") +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public void fun2() {\n" +
                myHandler.functionBody("fun2") +
                "\n" +
                "    }\n" +
                "\n" +
                "    @Override\n" +
                "    public void fun3() {\n" +
                myHandler.functionBody("fun3") +
                "    }\n" +
                "}\n";
        File file = new File(className + ".java");
        Files.writeString(file.toPath(), context);
        return file;
    }

    private static String getClassName() {
        return "MyInterface$proxy" + count.incrementAndGet();
    }

    //创建实例
    private static MyInterface newInstance(String className,MyHandler handler) throws Exception {
        Class<?> aClass = ProxyFactory.class.getClassLoader().loadClass(className);
        Constructor<?> constructor = aClass.getConstructor();
        MyInterface proxy = (MyInterface)constructor.newInstance();
        handler.setProxy(proxy);
        return proxy;
    }

    public static MyInterface createProxy(MyHandler myHandler) throws Exception {
        String className = getClassName();
        File javaFile = createJavaFile(className, myHandler);//生成java文件
        Compiler.compile(javaFile);//编译成class文件
        Object o = newInstance(packageName+"." + className, myHandler);
        return (MyInterface) o;
    }
}
